<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\AdminBaseController;
use Illuminate\Http\Request;
use Spatie\Permission\Models\Permission;

/**
 * 后台权限控制器
 * Class PermissionController
 * @package App\Http\Controllers\Admin
 */
class PermissionController extends AdminBaseController
{
    // 无需登录的方法
    protected $noNeedLogin = [];

    // 无需鉴权的方法
    protected $noNeedRight = ['permissionRoute'];

    /**
     * 查询权限列表
     * @return \Illuminate\Http\JsonResponse
     */
    public function index()
    {
        $permission = new Permission();
        $list = $permission->get()->toArray();
        $list = $this->tree($list);
        return $this->success($list);
    }

    /**
     * 管理员获取只属于自己的权限菜单
     */
    public function permissionRoute()
    {
        $user = auth('admin')->user();
        $list = $user->getAllPermissions()->toArray();
        $list = $this->tree($list);
        return $this->success($list);
    }

    /**
     * 新增权限
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(Request $request)
    {
        $param = $request->all();
        $permission = Permission::create($param);
        return $this->success($permission);
    }

    /**
     * 更新权限数据
     * @param Request $request
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(Request $request, $id)
    {
        $param = $request->all();
        $permission = Permission::findOrFail($id);
        $permission->fill($param)->save();
        return $this->success($permission);
    }

    /**
     * 删除权限
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy($id)
    {
        $permission = Permission::findOrFail($id);
        $permission->delete();
        $this->deleteTree($id);
        return $this->success(null, '删除权限成功');
    }

    /**
     * 删除权限同时删除子目录
     * @param $id
     */
    protected function deleteTree($id)
    {
        // 返回该权限的子权限id数组
        $ps = Permission::where('pid', '=', $id)->pluck('id');
        // 遍历删除子权限
        foreach ($ps as $p) {
            $permission = Permission::findOrFail($p);
            $permission->delete();
            // 查找该子权限是否有子权限
            self::deleteTree($p);
        }
    }
}
